package com.maoye.ossp.bpm.bpmweb.utils;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * <pre>
 * 嵌套表单提交数据缓存工具类
 * 	根据session创建内存空间
 * </pre>
 * 
 * @author hedh
 * 
 */
public final class NestedFormUtil {
	private static Map<String, DataHolder> dataMap = new HashMap<String, DataHolder>();

	/**
	 * 清理数据
	 */
	public static synchronized void clear() {
		dataMap.clear();
	}

	/**
	 * 在内存中创建表单数据缓存Map对象，此对象只允许读取一次
	 * 
	 * @param session
	 *            session
	 * @param keys
	 *            数据索引
	 * @return
	 */
	public static synchronized DataHolder createBySession(HttpSession session,
			String... keys) {
		DataHolder holder = dataMap.get(session.getId());
		if (holder != null) {
			holder = null;
			dataMap.remove(session.getId());
		}
		holder = new DataHolder(keys);
		dataMap.put(session.getId(), holder);
		return holder;
	}

	/**
	 * 获取session中的表单数据
	 * 
	 * @param session
	 * @return
	 */
	private static synchronized DataHolder getDataHolder(HttpSession session) {
		return dataMap.get(session.getId());
	}

	public static synchronized void clear(HttpSession session) {
		dataMap.remove(session.getId());
	}

	/**
	 * 获取数据缓存对象
	 * 
	 * @param request
	 * @return
	 */
	public static synchronized DataHolder getDataHolder(
			HttpServletRequest request) {
		DataHolder holder = getDataHolder(request.getSession());
		if (holder == null) {
			holder = NestedFormUtil.createBySession(request.getSession(),
					DataHolder.KEY_VARS, DataHolder.KEY_FORM, DataHolder.KEY_NODE);
			holder.setData(DataHolder.KEY_VARS, new HashMap<String, Object>());
		}
		return holder;
	}
}
